<?php

namespace app\common\model\Post;

use think\Model;
use traits\model\SoftDelete;

// 帖子模型
class Post extends Model
{
    // 软删除
    use SoftDelete;

    // 指定的数据表
    protected $name = 'post';

    // 自动写入时间
    protected $autoWriteTimestamp = true;

    // 创建时间
    protected $createTime = 'createtime';

    // 更新时间
    protected $updateTime = false;

    protected $deleteTime = 'deletetime';

    // 忽略数据表不存在的字段
    protected $field = true;

    //每次查询的时候，追加一个自定义字段
    protected $append = [
        'createtime_text',
        'comment_count',
        'collect_count'
    ];

    //收藏帖子的总人数
    public function getCollectCountAttr($value, $data)
    {
        //帖子id
        $postid = isset($data['id']) ? $data['id'] : 0;

        $where = [
            'postid' => $postid,
            'busid' => ['NOT NULL', '']
        ];

        return model('Post.Collect')->where($where)->count();
    }

    // 帖子评论总人数
    public function getCommentCountAttr($value, $data)
    {
        //帖子id
        $postid = isset($data['id']) ? $data['id'] : 0;

        $where = [
            'postid' => $postid,
            'busid' => ['NOT NULL', '']
        ];

        //查询评论人的总数
        $count = model('Post.Comment')->where($where)->group('busid')->count();

        // echo model('Post.Comment')->getLastSql();
        // exit;

        return $count;
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $createtime = isset($data['createtime']) ? $data['createtime'] : '';

        if(empty($createtime))
        {
            return '';
        }
        
        return date('Y-m-d H:i', $createtime);
    }

    public function business()
    {
        return  $this->belongsTo('app\common\model\Business\Business', 'busid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function accepted()
    {
        return  $this->belongsTo('app\common\model\Business\Business', 'accept', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function category()
    {
        return  $this->belongsTo('app\common\model\Post\Category', 'cateid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
